package com.huangwei.drivebook.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
    private static Connection connection = null;
    private static Properties properties = new Properties();
    private static DataSource dataSource = null;

    static {
        try {
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        try {
            if (connection == null || connection.isClosed()) {
                synchronized (JdbcUtils.class) {
                    if (connection == null || connection.isClosed()) {
                        connection = dataSource.getConnection();
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void close(Connection connection, Statement statement, ResultSet rs) {
        try {
            if (connection != null || !connection.isClosed()) {
                connection.close();
            }
            if (statement != null || !statement.isClosed()) {
                statement.close();
            }
            if (rs != null || !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Connection connection, ResultSet rs) {
        try {
            if (connection != null || !connection.isClosed()) {
                connection.close();
            }
            if (rs != null || !rs.isClosed()) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Connection connection) {
        try {
            if (connection != null || !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
